<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDA5g4Qya1aTfeHpQIupBXjkH977fOfbEI&sensor=false&libraries=places"></script>

 
</head>

<body> 

<div id="app"> 
<div class="mapcontrol">  
<div v-for="(o,index) in  placesList" > 
<span v-if="index==0">origin</span>
<span v-if="index==placesList.length-1">destination</span>
<span v-if="index!=0&&index!=placesList.length-1"><input type="button" value="-" @click="minus(index)" style="width: 32px"/></span>
  <input type="text"  v-model="o.v"  type="input"/>
</div>
 <input type="button" value="+" @click="add"  style="width: 32px" /> <input type="button" value="route" @click="findway" />
    <div id="warnings-panel"></div>
</div>
<div id="googleMap" ref="googleMap" style="width:100%;height:100%;"></div>

</div>
</body>
<script type="text/javascript">



 
 

var app = new Vue({
  el: '#app', 
  data:()=>({ 
    map:null,
    service:null,
    infowindow:null,
    directionsService:null,
    directionsRenderer:null,
    placesList:[
      {v:"125 Công xã Paris, Bến Nghé, Quận 1, Hồ Chí Minh"},
      {v:"10-12 Bình Phú, Phường 11, Quận 6, Hồ Chí Minh 700000"},
      {v:"112 Vo Thi Lieu Street, An Phu Dong Ward"}
    ], 
    markerArray:[],
    stepsArray:[]
  }), 
  mounted(){ 
      this.mapInit();  
  },
  methods:{  
    minus(index){
      this.placesList.splice(index,1);
      console.log(this.placesList)
    },
    add(){
      this.placesList.push({v:""})
    },
    mapInit(){

      var mapProp = {
        center: new google.maps.LatLng(15,108),
        zoom:6,
        panControl:true,
        zoomControl:true,
        mapTypeControl:true,
        scaleControl:true,
        streetViewControl:true,
        overviewMapControl:true,
        rotateControl:true,    
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      this.map=new google.maps.Map(this.$refs.googleMap,mapProp);
      this.infowindow = new google.maps.InfoWindow();
      this.directionsService = new google.maps.DirectionsService();
      this.directionsRenderer = new google.maps.DirectionsRenderer({ map: this.map });
    },
    createMarker(place) {  
      // const marker = new google.maps.Marker({      map:  this.map,position: place.geometry.location});
      const marker = new google.maps.Marker();
      marker.setPosition(place.geometry.location);
      google.maps.event.addListener(marker, "click", () => {
        this.infowindow.setContent(place.name+"<br/>lat:"+ place.geometry.location.lat()+" lng:"+ place.geometry.location.lng());
        this.infowindow.open(this.map,marker);
      }); 

      return marker;
    },
    findway(){ 

        // First, remove any existing markers from the map.
        for (let i = 0; i < this.stepsArray.length; i++) {
          this.stepsArray[i].setMap(null);
        }

        // First, remove any existing markers from the map.
        for (let i = 0; i < this.markerArray.length; i++) {
          this.markerArray[i].setMap(null);
        } 
        this.markerArray=[];
        this.stepsArray=[];
        this.placesList.forEach((p)=>{
            if(p.v=="")
              return;  
              const request = {
                query: p.v,
                fields: ["name", "geometry"]
              };
 
              service = new google.maps.places.PlacesService(this.map);

              service.findPlaceFromQuery(request, (results, status) => {
                  if (status === google.maps.places.PlacesServiceStatus.OK) {
                      let place=results[0]
                      let marker = this.createMarker(place);
 
                      this.markerArray.push(marker); 
                      this.map.setCenter(place.geometry.location);
                  } 
                  p.isFinish=true;



                  if(this.placesList.every((p)=>{
                      return p.isFinish==true;
                  })){

                    console.log("All finish");
                    this.calculateAndDisplayRoute()
                  } 
              });
        });


 


    },
    calculateAndDisplayRoute() { 
  // Retrieve the start and end locations and create a DirectionsRequest using
  // WALKING directions.
  
  const waypts = [];
  let origin=this.markerArray[0].position;
  let destination=this.markerArray[this.markerArray.length-1].position;

  for (var i = 1; i < this.markerArray.length-1; i++) {
    let m=this.markerArray[i];
    waypts.push({
        location: m.position,
        stopover: true
      });
  }



  this.directionsService.route(
    {
      origin: origin,
      destination: destination,
      waypoints: waypts,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING 
    },
    (result, status) => {
      // Route the directions and pass the response to a function to create
      // markers for each step.
      if (status === "OK") {
        document.getElementById("warnings-panel").innerHTML =
          "<b>" + result.routes[0].warnings + "</b>";
        this.directionsRenderer.setDirections(result);
        // this.showSteps(result);
      } else {
        window.alert("Directions request failed due to " + status);
      }
    }
  );
},
showSteps(directionResult) {
  // For each step, place a marker, and add the text to the marker's infowindow.
  // Also attach the marker to an array so we can keep track of it and remove it
  // when calculating new routes.
  
      var image = '<svg t="1597381301867" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7892" width="20" height="20"><path d="M501.76 963.84c-6.912 0-12.672-5.248-13.184-12.16L458.88 618.24h85.76l-29.696 333.44c-0.512 6.912-6.272 12.16-13.184 12.16z" fill="#C5C5C5" p-id="7893"></path><path d="M458.88 618.24l4.48 50.176c13.568 3.968 28.416 6.144 44.16 6.144 11.264 0 22.144-1.152 32.384-3.2l4.736-53.12h-85.76z" fill="#9F9F9F" p-id="7894"></path><path d="M212.48 350.72a289.28 289.28 0 1 0 578.56 0 289.28 289.28 0 1 0-578.56 0z" fill="#FC6C6E" p-id="7895"></path><path d="M440.32 350.72a61.44 61.44 0 1 0 122.88 0 61.44 61.44 0 1 0-122.88 0z" fill="#E14444" p-id="7896"></path></svg>';

      for (var k = 0; k <  directionResult.routes.length; k++) {
         const route= directionResult.routes[k]

         for (var j = 0; j < route.legs.length; j++) {
           const myRoute=route.legs[j];


       

        for (let i = 0; i < myRoute.steps.length; i++) {

          const marker = new google.maps.Marker();
          marker.setMap(this.map);
          marker.setPosition(myRoute.steps[i].start_location);
          // marker.setIcon(image )

          marker.setIcon({ url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(image), scaledSize: new google.maps.Size(20, 20) })
          this.stepsArray.push(marker)
          this.attachInstructionText(
            marker,
            myRoute.steps[i].instructions
          );
          console.log("xx   "+myRoute.steps[i].start_location.lat()+","+myRoute.steps[i].start_location.lng()+";"+myRoute.steps[i].instructions)
        }



         }


      }



},
attachInstructionText( marker, text) {
  google.maps.event.addListener(marker, "click", () => {
    // Open an info window when the marker is clicked on, containing the text
    // of the step. 
    this.infowindow.setContent(text+"<br/>lat:"+ marker.position.lat()+" lng:"+ marker.position.lng());

    this.infowindow.open(this.map, marker);
  });
}
  }
})
 


</script>
</html>